package com.scut.shangxueguan.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.scut.shangxueguan.mapper.FileMapper;
import com.scut.shangxueguan.pojo.Files;
import com.scut.shangxueguan.pojo.Result;
import com.scut.shangxueguan.service.IFileService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
@Service
public class FileServiceImpl implements IFileService {

    private final FileMapper fileMapper;

    @Value("${file.root.path}")
    private String parentPath;

    @Override
    public Result<List<Files>> uploadFile(MultipartFile[] files) {
        if(files == null || files.length == 0) {
            return Result.error("文件不能为空！");
        }

        List<Files> msgList = new ArrayList<>();

        for(MultipartFile file : files) {
            String originalFileName = file.getOriginalFilename();
            String mainFileName = FileUtil.mainName(originalFileName);
            String extendFileName = FileUtil.extName(originalFileName);
            long filesize = file.getSize();

            File dest = null;

            try {
                // 没有跟上一级目录就创建
                if(FileUtil.exist(parentPath)){
                    FileUtil.mkdir(parentPath);
                }

                String fileName = UUID.randomUUID().toString() + '_' + mainFileName + '.' + extendFileName;

                // 文件保存的目标路径
                String filePath = parentPath + File.separator + fileName;
                dest = new File(filePath);

                file.transferTo(dest);

                Files fileInfo = Files.builder().name(filePath).size(filesize).createTime(LocalDateTime.now()).build();
                msgList.add(fileInfo);

                fileMapper.insertFile(fileInfo);
            } catch (IOException e) {
                log.error(e.getMessage());
                return Result.error("文件上传失败！");
            }
        }
        // 最后是返回文件路径
        return Result.success(msgList);
    }

    @Override
    public Result downloadFile(String fileName, HttpServletResponse response) throws IOException {
        if (!FileUtil.exist(fileName)) {
            return Result.error("文件不存在！");
        }

        BufferedOutputStream bos = null;
        try {
            byte[] bytes = FileUtil.readBytes(fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            bos = new BufferedOutputStream(outputStream);
            bos.write(bytes);  // 数组是一个字节数组，也就是文件的字节流数组
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            bos.close();
        }

        return Result.success();
    }

    @Override
    public List<Files> getAllFile() {
        return fileMapper.getAllFile();
    }

    @Override
    public Result deleteFile(String fileName) {
        File file1 = new File(fileName);
        if(!file1.exists()) {
            return Result.error("文件不存在！");
        }
        file1.delete();
        fileMapper.deleteFile(fileName);
        return Result.success();
    }

}
